<template>
  <div class="container">
    <div class="titleTop">
      <div>
        <el-radio-group v-removeAriaHidden v-model="listType" size="small" @input="handleListType">
          <el-radio-button label="下载列表"></el-radio-button>
          <el-radio-button label="上传列表"></el-radio-button>
        </el-radio-group>
      </div>
      <div>
        <el-button icon="el-icon-delete" size="small" @click="clearRecord">清空记录</el-button>
      </div>
    </div>
    <div class="empty">
      <el-empty :description="listType=='下载列表'?'当前没有下载记录':'当前没有上传任务'" v-if="tableData.length==0"
      ></el-empty>
    </div>
    <div class="tableList" v-loading="loading">
      <el-table
        v-show="tableData.length>0"
        :data="tableData"
        style="width: 100%;"
        ref="scrollTable"
        height="100%"
      >
        <el-table-column
          prop="fileName"
          align="left"
          label="文件名"
          width="400"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div class="fileName">
              <img
                :src="FileImage[scope.row.extendName]? FileImage[scope.row.extendName]:require('@/assets/image_library/netmini.png')"
              />
              <div>{{ scope.row.fileName + '.' + scope.row.extendName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="fileSize"
          label="大小"
          align="center"
        >
          <template slot-scope="scope">
            {{ convertBytes(scope.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          :label="listType==='下载列表'?'下载时间':'上传时间'"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime | fifterTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-delete" type="text"
                       @click="deleteByid(scope.row.downloadTaskId||scope.row.uploadTaskId)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <fileDrawer
      :show.sync="drawer"
      :url="drawerurl"
      :name="drawername"
      :type="drawertype"
    ></fileDrawer>
  </div>
</template>

<script>
import { clearDownloadRecord, clearUploadRecord, deleteTransferRecord, downloadRecord, uploadRecord } from '@/api/library_filrList/fileList'
import videoReview from '@/views/library_homePage/component/videoReview.vue'
import fileDrawer from '@/components/fileDrawer.vue'
import { convertBytes } from '@/views/library_homePage/utils/files'

export default {
  name: 'filePage',
  components: { videoReview, fileDrawer },
  // 过滤时间
  filters: {
    fifterTime(value) {
      if (!value) return ''
      const time = new Date(value)
      const newDate = new Date(
        time.getFullYear(),
        time.getMonth(),
        time.getDate(), // 减一天
        time.getHours() + 8,
        time.getMinutes(),
        time.getSeconds()
      )
      return newDate.toISOString().replace('T', ' ').slice(0, 19).replace('T', ' ')
    }

  },
  data() {
    return {
      convertBytes: function(num) {
        return convertBytes(num)
      },
      listType: '下载列表',
      drawer: false,
      drawerurl: '',
      drawername: '',
      drawertype: '',
      tableData: [],
      sea_form: {
        pageNum: 1,
        pageSize: 60
      },
      total: 0,
      loading: false,
      FileImage: {
        'pdf': require('@/assets/image_library/pdfmini.png'),
        'docx': require('@/assets/image_library/wordmini.png'),
        'dov': require('@/assets/image_library/wordmini.png'),
        'xls': require('@/assets/image_library/excelmini.png'),
        'xlsx': require('@/assets/image_library/excelmini.png'),
        'ppt': require('@/assets/image_library/pptmini.png'),
        'pptx': require('@/assets/image_library/pptmini.png'),
        'txt': require('@/assets/image_library/textmini.png'),
        'zip': require('@/assets/image_library/zipmini.png'),
        'rar': require('@/assets/image_library/zipmini.png'),
        'mp3': require('@/assets/image_library/musicmini.png'),
        'mp4': require('@/assets/image_library/videomini.png')
      }
    }
  },
  mounted() {
    this.listType = '下载列表'
    this.getList()
    this.loadMoreData = this.debounce(this.loadMoreData, 500)
    /**
     * @description:添加分页加载滚动事件
     * @return {*}
     */
    let table = this.$refs.scrollTable.bodyWrapper
    table.addEventListener('scroll', (e) => {
      const { scrollTop, clientHeight, scrollHeight } = e.target
      // 检查是否滚动到底部
      if (scrollHeight - scrollTop <= clientHeight) {
        this.loadMoreData()
      }
    })
  },
  methods: {
    handleListType() {
      this.sea_form.pageNum = 1
      this.getList()
    },
    debounce(fn, delay, immediate = false) {
      let timer
      return function(...args) {
        const context = this
        if (immediate && !timer) {
          fn.apply(context, args)
        }
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          if (!immediate) {
            fn.apply(context, args)
          }
          timer = null
        }, delay)
      }
    },
    loadMoreData() {
      if (this.total > this.tableData.length) {
        this.sea_form.pageNum++
        this.getList()
      } else {
        console.log('没有更多数据了')
      }
    },
    getList() {
      if (this.listType === '下载列表') {
        this.getdownLoadList()
      } else {
        this.getFilelist()
      }
    },

    async getFilelist() {
      if (this.sea_form.pageNum == 1) {
        this.loading = true
      }
      let res = await uploadRecord(this.sea_form)
      if (res.code == 200) {
        this.total = res.total
        if (this.sea_form.pageNum == 1) {
          this.tableData = res.rows
        } else {
          this.tableData.push(...res.rows)
        }
        this.tableData.map((item, index) => ({
          ...item,
          index: index + 1
        }))
      }
      this.loading = false
    },
    async getdownLoadList() {
      if (this.sea_form.pageNum == 1) {
        this.loading = true
      }
      let res = await downloadRecord(this.sea_form)

      if (res.code == 200) {
        this.total = res.total
        if (this.sea_form.pageNum == 1) {
          this.tableData = res.rows
        } else {
          this.tableData.push(...res.rows)
        }
        this.tableData.map((item, index) => ({
          ...item,
          index: index + 1
        }))
      }
      this.loading = false
    },
    clearRecord() {
      if (this.listType === '下载列表') {
        this.cleardownloadList()
      } else {
        this.clearuploadList()
      }
    },
    async cleardownloadList() {
      let res = await clearDownloadRecord()
      if (res.code == 200) {
        this.$message.success('清除成功')
        this.handleListType()
      }
    },
    async clearuploadList() {
      let res = await clearUploadRecord()
      if (res.code == 200) {
        this.$message.success('清除成功')
        this.handleListType()
      }
    },
    deleteByid(id) {
      if (this.listType === '下载列表') {
        this.deleteRecord(2, id)
      } else {
        this.deleteRecord(1, id)
      }
    },
    // 删除下载上传记录
    async deleteRecord(type, ids) {
      // type=1 上传 type=2下载
      let res = await deleteTransferRecord(type, ids)
      if (res.code == 200) {
        this.$message.success('删除成功')
        this.handleListType()
      }
    },
    // handleRowClick(row){
    //   this.lookFiles(row.fileUrl, '.'+row.extendName)
    // },
    lookFiles(url, uploadType) {
      let arr = [
        '.gif',
        '.png',
        '.jpeg',
        '.jpg',
        '.mp4',
        '.webm',
        '.pdf',
        '.wps',
        '.docx',
        '.doc',
        '.rtf',
        '.pptx',
        '.ppt',
        '.xls',
        '.xlsx',
        '.wps',
        '.ofd',
        '.txt',
        '.js',
        '.json',
        '.css',
        '.sql',
        '.xml',
        '.java',
        '.cs(c#)'
      ]
      if (arr.indexOf(uploadType) > -1) {
        this.drawer = true
        this.drawerurl = url
        this.drawername = name
        this.drawertype = 1
      } else if (uploadType == '.mp3') {
        window.open(url, '_blank')
      } else {
        this.$message.info('暂不支持在线预览，请下载后查看')
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: calc(100vh - 60px);
  background-color: #ffffff;
  position: relative;

  .titleTop {
    height: 50px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
    box-sizing: border-box;
    border-bottom: 1px solid #dddddd;
  }

  .empty {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .fileName {
    display: flex;
    align-items: center;

    img {
      width: 15px;
      height: 16px;
      margin-right: 10px;
    }
  }

  .tableList {
    height: calc(100vh - 110px);
    overflow: hidden;
  }
}

</style>
